//
//  WNEarnVC.swift
//  WalkNovel
//
//  Created by Kevin on 2023/7/6.
//

import UIKit

class WNEarnVC: WNBaseVC {
    
    lazy var goldView: EarnGoldView = {
        let view = EarnGoldView()
        return view
    }()
    
    lazy var ticketView: EarnTicketView = {
        let view = EarnTicketView()
        view.checkClosure = { [weak self] in
            self?.ticketRequest()
        }
        return view
    }()
    
    lazy var rewardBtn: UIButton = {
        let btn = UIButton(type: .custom)
        btn.setImage(UIImage(named: "rank_reward"), for: .normal)
        btn.setImage(UIImage(named: "rank_reward"), for: .highlighted)
        btn.rx.tap.bind { [weak self] in
            self?.navigationController?.pushViewController(WNDrawVC(), animated: true)
        }.disposed(by: rx.disposeBag)
        btn.isHidden = true
        return btn
    }()
    
    var ticketArr = [TicketModel]() {
        didSet {
            ticketView.ticketArr = ticketArr
            ticketView.checkBtn.isEnabled = false
            ticketView.checkBtn.backgroundColor = .init(named: "gray_E0E8EE")
            saveHasCheck(true)
            for i in ticketArr {
                if i.status == 2 {
                    ticketView.checkBtn.isEnabled = true
                    ticketView.checkBtn.backgroundColor = .init(named: "red_FE6390")
                    saveHasCheck(false)
                }
            }
        }
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        getEarnUserGold()
    }

    override func viewDidLoad() {
        super.viewDidLoad()
    }
    
    override func viewConfig() {
        view.backgroundColor = .init(named: "white_F7F7F7")
        view.addSubview(goldView)
        view.addSubview(ticketView)
        view.addSubview(rewardBtn)
        goldView.snp.makeConstraints { make in
            make.top.equalTo(NaviTotalHeight+15)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(144)
        }
        ticketView.snp.makeConstraints { make in
            make.top.equalTo(goldView.snp.bottom).offset(15)
            make.left.equalTo(15)
            make.right.equalTo(-15)
            make.height.equalTo(275)
        }
        rewardBtn.snp.makeConstraints { make in
            make.top.equalTo(ticketView.snp.bottom).offset(15)
            make.left.right.equalTo(0)
            make.height.equalTo(ScreenW*0.333)
        }
    }
    
    override func dataConfig() {
        pageName = "Earn Rewards"
        navView.titleName = "Earn Rewards"
        getTicketInfo()
    }
}

extension WNEarnVC {
    
    func getEarnUserGold() {
        getUserGold { [weak self] balance in
            let gold = "\(WNSingleData.shared.userGold)"
            self?.goldView.goldCount.text = gold
            let w = wn_getTextW(textStr: gold, font: .wn_font(name: .bold, size: 40), height: 40)*0.5
            self?.goldView.headerImage.snp.updateConstraints { make in
                make.centerX.equalToSuperview().offset(-8-w)
            }
            self?.goldView.headerImage.wn_setupImg(getUser()?.avatar, placeHolder: "placeholder_header")
        }
    }
    
    func getTicketInfo() {
        provider_user.rx.request(.checkTicket)
            .asObservable().mapModel(BaseModel<[TicketModel]>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else { return }
                if let arr = model.data {
                    self?.ticketArr = arr
                }
            }, onError: { (error) in
            }).disposed(by: rx.disposeBag)
    }
    
    func ticketRequest() {
        let ticket = ticketArr.filter({$0.status == 2}).first
        provider_user.rx.request(.ticket(ticket?.day ?? 0, ticket?.gold ?? 0))
            .asObservable().mapModel(BaseModel<Any>.self)
            .subscribe(onNext: { [weak self] (model) in
                guard model.code == 0 else {
                    self?.wn_toast(model.msg ?? "")
                    return
                }
                if model.data != nil {
                    self?.getTicketInfo()
                    self?.getEarnUserGold()
                    self?.wn_toast("Check in successed")
                    WNBuriedManager.shared.checkIn("\(ticket?.day ?? 0)")
                }
            }, onError: { [weak self] (error) in
                self?.wn_toast("Check the network connection")
            }).disposed(by: rx.disposeBag)
    }
}
